package conversation

import (
	"fmt"

	"gopkg.in/xmlpath.v2"

	"code.google.com/awwwe-browser/scrub"
	"code.google.com/awwwe-browser/scrub/htmlsoup"
	"code.google.com/awwwe-browser/xpath"
)

var videoEmbedXpaths = [...]string{
	`.//iframe[contains(@src, "www.break.com/embed/")]`,
	`.//iframe[contains(@src. "www.ustream.tv/embed/")]`,
	`.//iframe[contains(@src, "www.twitch.tv/")]`,
	`.//object[@type="application/x-shockwave-flash" and contains(@data, ".liveleak.com")]`,
	`.//iframe[contains(@src, "www.youtube.com/embed/")]`,
	`.//iframe[contains(@src, "player.vimeo.com/video/")]`,
	`.//video`}

func getVideoSoupNodes(textnodes []*xmlpath.Node, scrubber *scrub.Scrubber, tree *xmlpath.Node, xpath string) []*htmlsoup.SoupNode {
	var fnodes, filternodes []*htmlsoup.SoupNode
	var fnode *htmlsoup.SoupNode
    var textnode *xmlpath.Node
	filternodes = make([]*htmlsoup.SoupNode, 0, 5)
	for _, textnode = range textnodes {
		// get the anchor nodes in the article text nodes
		fnodes = MatchXpathToTreeNodes(scrubber, textnode, xpath)
		for _, fnode = range fnodes {
			filternodes = append(filternodes, fnode)
		}
	}
    return filternodes
}

func buildVideoSoupNodes(scrubber *scrub.Scrubber, tree *xmlpath.Node, onlyspeakat string) []*htmlsoup.SoupNode {
	var textnodes []*xmlpath.Node
	var fnodes, filternodes []*htmlsoup.SoupNode
	var fnode *htmlsoup.SoupNode
    var path string
	filternodes = make([]*htmlsoup.SoupNode, 0, 5)
	textnodes = xpath.PathNodesString(onlyspeakat, tree)
	for _, path = range videoEmbedXpaths {
		fnodes = getVideoSoupNodes(textnodes, scrubber, tree, path)
		for _, fnode = range fnodes {
			filternodes = append(filternodes, fnode)
		}
	}
	return filternodes
}

// BuildSpeechArticleVideos builds video markup it finds in an article for a article videos conversation.
func (this *Conversation) BuildSpeechArticleVideos(scrubber *scrub.Scrubber, tree *xmlpath.Node, onlyspeakat string, tabkey int, sourceobject, sourcemethod string, sourcestartindex int) {
	var filternodes []*htmlsoup.SoupNode
	var filternode *htmlsoup.SoupNode
	var video VideoOption
	var vxml, markup string
	var i int
	// get the video nodes
	filternodes = buildVideoSoupNodes(scrubber, tree, onlyspeakat)
	i = 0
	for _, filternode = range filternodes {
		markup = filternode.String()
		if len(markup) > 0 {
			video = BuildVideoOption()
			video.Markup = markup
			i++
			vxml = fmt.Sprintf("video number %d.", i)
			// vxml = strings.Replace(vxml, data.VXMLLongPauseString, " ", -1)
			// vxml = strings.Trim(vxml, data.WhiteSpaceString)
			video.VXMLs.Append(vxml)
			this.Videos = append(this.Videos, video)
		}
	}
}
